﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccessObjectLayer;
using BusinessObjectLayer;
using System.IO;
using System.Net;
using DataAccessLayer;

namespace DataAccessLibrary
{
    public class FileDAL
    {
        private static FileDOL.CommandStatus commandStatus;
        private static FileBOL _FileBOL;
        public FileDAL(FileDOL.CommandStatus CommandStatus)
        {
            commandStatus = CommandStatus;
        }
        public FileDAL(FileDOL.CommandStatus CommandStatus, FileBOL fileBOL)
        {
            commandStatus = CommandStatus;
            _FileBOL = fileBOL;
        }
        public string ReadText()
        {
            WebClient request = new WebClient();
            request.Credentials = new NetworkCredential(ServerDAL.GetStringValue("UserName"), ServerDAL.GetStringValue("Password"));
            byte[] newFileData = request.DownloadData(URL(_FileBOL.Path));
            return System.Text.Encoding.UTF8.GetString(newFileData);
        }
        private string URL(string path)
        {
            string serverPath = ServerDAL.GetStringValue("ServerPath");
            string domain = ServerDAL.GetStringValue("Domain");
            return string.Format("ftp://{0}/{1}/{2}", serverPath, domain,path);
        }
        public void Write()
        {
            WebClient request = new WebClient();
            request.Credentials = new NetworkCredential(ServerDAL.GetStringValue("UserName"), ServerDAL.GetStringValue("Password"));
            request.UploadFile(string.Format("{0}{1}", URL(_FileBOL.Path), _FileBOL.Destination), _FileBOL.Source);
        }
        public void DownloadFiles()
        {
            string[] serverFiles = FileNames();
            RemoveExtraFiles(serverFiles);
            foreach (string file in serverFiles)
                Download(file);
        }
        private void RemoveExtraFiles(string[] serverFiles)
        {
            string localPath = ServerDAL.GetStringValue("TempPath") + "\\Gallery";
            string[] localFilesName = Directory.GetFiles(localPath);
            foreach (string file in localFilesName)
            {
                if (serverFiles.Count(item => item == file.Replace(localPath,"").Replace("\\","")) == 0)
                    File.Delete(file);
            }    
        }
        private void Download(string file)
        {
            try
            {
                string uri = string.Format("{0}/{1}", URL(_FileBOL.Path), file);
                string localFile = ServerDAL.GetStringValue("TempPath") + "\\Gallery\\" + file;
                if (File.Exists(localFile))
                    return;
                Uri serverUri = new Uri(uri);
                if (serverUri.Scheme != Uri.UriSchemeFtp)
                {
                    return;
                }
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));                                
                reqFTP.Credentials = new NetworkCredential(ServerDAL.GetStringValue("UserName"), ServerDAL.GetStringValue("Password"));
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Proxy = null;
                reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream responseStream = response.GetResponseStream();
                FileStream writeStream = new FileStream(localFile, FileMode.Create);
                int Length = 2048;
                Byte[] buffer = new Byte[Length];
                int bytesRead = responseStream.Read(buffer, 0, Length);
                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = responseStream.Read(buffer, 0, Length);
                }
                writeStream.Close();
                response.Close();
            }
            catch { }
        }
        public string[] FileNames()
        {
            StringBuilder result = new StringBuilder();
            string folderPath = URL(_FileBOL.Path);
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(folderPath);
            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(ServerDAL.GetStringValue("UserName"), ServerDAL.GetStringValue("Password"));
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();    
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);            
            string line = reader.ReadLine();
            while (line != null)
            {
                result.Append(line);
                result.Append("\n");
                line = reader.ReadLine();
            }
            reader.Close();
            response.Close();
            result.Remove(result.ToString().LastIndexOf('\n'), 1);
            return result.ToString().Split('\n');                   
        }
        public void Delete()
        {            
            string uri = URL(_FileBOL.Destination);
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
            request.Method = WebRequestMethods.Ftp.DeleteFile;
            request.Credentials = new NetworkCredential(ServerDAL.GetStringValue("UserName"), ServerDAL.GetStringValue("Password"));
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            File.Delete(_FileBOL.Source);
        }
        private string FileName(string path)
        {
            return path.Substring(path.LastIndexOf("/")).Replace("/","");
        }
    }
}
